package net.jam.loader;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class ParamLoader {

	private String prefix = "";

	public ParamLoader(String prefix) {
		this.prefix = prefix;
	}

	private String referer = "http://www.google.com/#hl=en&source=hp&q=runescape&btnG=Google+Search&meta=&aq=f&oq=runescape&fp=324c8a90db775e43";
	public final HashMap<String, String> parameters = new HashMap<String, String>();

	private String readPage(URL url) throws IOException, InterruptedException {
		String s = readPage(url, referer);
		referer = url.toExternalForm();
		return s;
	}

	private String readPage(URL url, String referer) throws IOException, InterruptedException {
		URLConnection uc = url.openConnection();
		uc.addRequestProperty("Accept",
				"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
		uc.addRequestProperty("Accept-Charset",
		"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		uc.addRequestProperty("Accept-Encoding", "gzip,deflate");
		uc.addRequestProperty("Accept-Language", "en-gb,en;q=0.5");
		uc.addRequestProperty("Connection", "keep-alive");
		uc.addRequestProperty("Host", "www.runescape.com");
		uc.addRequestProperty("Keep-Alive", "300");
		if (referer != null)
			uc.addRequestProperty("Referer", referer);
		uc.addRequestProperty("User-Agent",
		"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6");
		DataInputStream di = new DataInputStream(uc.getInputStream());
		byte[] buffer = new byte[uc.getContentLength()];
		di.readFully(buffer);
		di.close();
		return new String(buffer);
	}

	public final void loadParams() throws MalformedURLException, IOException, InterruptedException {
		String html = readPage(new URL("http://" + prefix + ".runescape.com/a2,m0,j0,o0"));
		try {
			Pattern regex = Pattern.compile("<param name=([^\\s]+)\\s+value=\"{0,1}(.*?)\"{0,1}>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
			Matcher regexMatcher = regex.matcher(html);
			while (regexMatcher.find())
				if (!parameters.containsKey(regexMatcher.group(1)))
					parameters.put(regexMatcher.group(1), regexMatcher.group(2));
		} catch (PatternSyntaxException ex) {
			ex.printStackTrace();
		}
	}
	
	public HashMap<String, String> params() {
		return this.parameters;
	}

}
